import PlanAPI from '@/api/Plan';
import ProductAPI from '@/api/Product';
import {
  Box,
  FieldCols,
  FieldTable,
  FormSection,
  mapField,
  useCall,
  useFormValue,
  useQueryValue,
  useReq,
  useSimpleMemo,
} from '@/components';
import { SelectProduct } from '@/pages/components';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Form, message, Space, Spin } from 'antd';
import React, { createContext, useContext, useEffect } from 'react';

const FIELDS = [
  ['planCode', '计划编码', null, { required: true, extra: '猎户座Code' }],
  ['planName', '计划名称', null, { required: true }],
].map(mapField);

const COL_FIELDS = [
  ['productCode', '险种编码', 'plain', { width: 160 }],
  ['productName', '险种名称', 'plain'],
  [['productInsure', 'singleCoverage'], '保额', 'plain', { width: 140 }],
  [['productInsure', 'minCoverageLimit'], '最低保额', 'plain', { width: 140 }],
  [['productInsure', 'maxCoverageLimit'], '最高保额', 'plain', { width: 140 }],
].map(mapField);

const Context = createContext({ planBusinessCode: null, premiumAddType: null });

function RequestProducts() {
  const { form } = useContext(Context);
  const selected = useFormValue(form, 'products', (v) => v?.map((t) => t.productCode) ?? []);
  const onSelect = useCall(async (prodList) => {
    if (prodList.every((i) => i.productType !== '1')) {
      message.warn('请至少选择一款主险');
      return false;
    }
    const data = await ProductAPI.selectProductDetailList(prodList.map((v) => v.productCode));
    if (data?.data) {
      form.setFieldsValue({ products: data.data });
    }
  });

  return (
    <>
      <Box>
        <SelectProduct selectType='checkbox' rowKey='productCode' selectedKeys={selected} onOk={onSelect}>
          <Button type='primary'>+ 新 增</Button>
        </SelectProduct>
        <Box py={2} />
      </Box>
      <FieldTable name='products' form={form} fields={COL_FIELDS} showRemoveBtn />
    </>
  );
}

function AddPage({ history }) {
  const planBusinessCode = useQueryValue('planBusinessCode');
  const xhr = useReq(PlanAPI.getByCode);
  const saveXhr = useReq(PlanAPI.insertOrUpdate);
  const [form] = Form.useForm();

  useEffect(() => {
    if (planBusinessCode) {
      xhr.start(planBusinessCode).then((res) => {
        if (res.data) form.setFieldsValue(res.data);
      });
    }
  }, [planBusinessCode]);

  const context = useSimpleMemo({ form, planBusinessCode });

  const loading = [xhr.status, saveXhr.status].includes('loading');

  const handleSave = useCall(async () => {
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    if (!values.products?.length) {
      message.warn('请至少添加一个险种');
      return false;
    }

    await saveXhr.start({ ...(xhr.result?.data ?? null), ...values });

    message.success('保存成功');
    history.goBack();
  });

  return (
    <Context.Provider value={context}>
      <Spin spinning={loading}>
        <Form form={form}>
          <FormSection title='计划'>
            <FieldCols form={form} fields={FIELDS} />
          </FormSection>

          <FormSection title='险种'>
            <RequestProducts />
          </FormSection>
        </Form>

        <Box flex jus='center' py={3} className='form-page-btn'>
          <Space size='large'>
            <Button onClick={history.goBack}>返回</Button>
            <Button type='primary' onClick={handleSave}>
              保存
            </Button>
          </Space>
        </Box>
      </Spin>
    </Context.Provider>
  );
}

export default AddPage;
